package com.beiwei.controller;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.beiwei.auto.mode.Department;
import com.beiwei.auto.mode.Job;
import com.beiwei.service.DepartmentService;
import com.beiwei.service.JobService;

@Controller
@RequestMapping("/job")
public class JobHandler {
	@Autowired
	private JobService jobService;
	@Autowired
	private DepartmentService departmentService;

	/**
	 * 进入新加岗位页面
	 */
	@RequestMapping("/add/{departmentId}")
	@RequiresPermissions("department:create")
	public String add(@PathVariable("departmentId") Integer departmentId, Model model) {
		Job job = new Job();
		job.setJobDepartmentId(departmentId);

		Department department = null;
		try {
			department = departmentService.findDepartmentByDepartmentId(departmentId);
		} catch (Exception e) {
			e.printStackTrace();
		}
		model.addAttribute("job", job);
		model.addAttribute("department", department);
		return "editJob";
	}

	/**
	 * 保存新加岗位
	 */
	@RequestMapping(value = "/save", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
	@RequiresPermissions("department:create")
	@ResponseBody
	public String save(Job job) {
		try {
			if (jobService.addJob(job)) {
				return "success";
			}

		} catch (Exception e) {
			e.printStackTrace();
		}

		return "操作失败！";
	}

	/**
	 * 进入到更新岗位页面
	 */
	@RequestMapping("/edit/{jobId}")
	@RequiresPermissions("department:update")
	public String edit(@PathVariable("jobId") Integer jobId, Model model) {
		Job job = null;
		Department department = null;
		try {
			job = jobService.findJobByJobId(jobId);
			department = (job == null) ? null : (departmentService.findDepartmentByDepartmentId(job.getJobDepartmentId()));
		} catch (Exception e) {
			e.printStackTrace();
		}

		model.addAttribute("job", job);
		model.addAttribute("department", department);

		return "editJob";
	}

	/**
	 * 更新保存
	 */
	@RequestMapping(value = "/save", method = RequestMethod.PUT, produces = "application/json; charset=utf-8")
	@RequiresPermissions("department:update")
	@ResponseBody
	public String editSave(Job job) {
		try {
			if (jobService.saveJob(job)) {
				return "success";
			}

		} catch (Exception e) {
			e.printStackTrace();
		}

		return "操作失败！";
	}
}
